package com.dqyt.khjc.sms;
import java.security.SecureRandom;
import java.util.Random;

import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sms.v20190711.SmsClient;
import com.tencentcloudapi.sms.v20190711.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20190711.models.SendSmsResponse;
import com.tencentcloudapi.sms.v20190711.models.SendStatus;

/**
 * 短信帮助类
 * 
 * @author 王植平
 * @version 1.0
 * @date 创建时间：2020年1月18日 下午3:25:50
 * @parameter
 * @since
 * @return
 *
 */
public class SMSTool {

	/**
	 * 实例化一个认证对象
	 */
	private static final Credential cred = new Credential("AKIDBJBn9E3brqZonVx81dy2oKYWDckcDckb", "cx1oLaYFfogGZbMr40g5D5g03tTmoY1n");
	
	private static final String SYMBOLS = "0123456789"; // 数字
	private static final Random RANDOM = new SecureRandom();

	public static void init() {
//		try {
////			cred = new Credential("AKIDnNgkY8KBftrXy9knEOkLfHcCWZLql5mD", "KPFNGvJQHuIPGreDVZNxGI5cssTqyqRh");
//		} catch (Exception e) {
////			cred = null;
////			e.printStackTrace();
//		}
	}

	/**
	 * 发送短信
	 * 
	 * @param params
	 * @return 返回为null，表示发送失败
	 */
	public static SendSmsResponse sendSMS(String params) {
		if (cred == null) {
			return null;
		}
		SendSmsResponse resp = null;
		try {
			HttpProfile httpProfile = new HttpProfile();
			httpProfile.setEndpoint("sms.tencentcloudapi.com");

			ClientProfile clientProfile = new ClientProfile();
			clientProfile.setHttpProfile(httpProfile);

			SmsClient client = new SmsClient(cred, "", clientProfile);
			SendSmsRequest req = SendSmsRequest.fromJsonString(params, SendSmsRequest.class);

			resp = client.SendSms(req);
		} catch (TencentCloudSDKException e) {
			//System.out.println(e.toString());
		}
		return resp;

	}

	/**
	 * 判断短信是否发送成功
	 * 
	 * @param resp
	 * @return
	 */
	public static boolean isSendSMSOK(SendSmsResponse resp) {
		if (null == resp) {
			return false;
		} else {
			SendStatus[] status = resp.getSendStatusSet();
			boolean ret = false;
			for (SendStatus statu : status) {
				if ("Ok".equals(statu.getCode())) {
					ret = true;
					break;
				}
			}
			return ret;
		}
	}
	

	
	/**
	 * 获取长度为 6 的随机数字
	 * @return 随机数字
	 * 
	 */
	public static String getNonce_str() {
		// 如果需要4位，那 new char[4] 即可，其他位数同理可得
		char[] nonceChars = new char[6];
		for (int index = 0; index < nonceChars.length; ++index) {
			nonceChars[index] = SYMBOLS.charAt(RANDOM.nextInt(SYMBOLS.length()));
		}
		return new String(nonceChars);
	}

}
